<template>
  <div class="p-3">
    <a-card style="height: 820px" :bordered="false">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="操作时间" name="operatingTime">
          <a-range-picker style="width: 250px"></a-range-picker>
        </a-form-item>
        <a-form-item label="归属机构" name="comId">
          <a-tree-select
            v-model:value="searchForm.comId"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择归属机构"
          />
        </a-form-item>
        <a-form-item label="操作人" name="operator">
          <a-tree-select
            v-model:value="searchForm.operator"
            tree-data-simple-mode
            allow-clear
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="selectList"
            placeholder="请选择操作人"
            :load-data="onLoadData"
          />
        </a-form-item>
        <a-form-item label="协议名称" name="protocol">
          <a-input style="width: 150px" placeholder="请输入协议名称"></a-input>
        </a-form-item>
        <a-form-item label="协议类型" name="protocolType">
          <a-select style="width: 150px" placeholder="请选择协议类型">
            <a-select-option :value="0">供热协议</a-select-option>
            <a-select-option :value="1">停供协议</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSearch"
            ><SearchOutlined />查询</a-button
          >
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="showAddModal"
            ><PlusOutlined />新增</a-button
          >
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        class="mt-3"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'protocolType'">
            {{ record.protocolType == 0 ? '供热协议' : '停供协议' }}
          </template>
          <template v-if="column.dataIndex == 'action'">
            <a-button type="link" @click="showEditModal(record)">编辑</a-button>
            <a-popconfirm
              title="确定删除该合同吗？"
              placement="bottom"
              ok-text="是"
              cancel-text="否"
              @confirm="confirmDelete(record.id)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑合同弹窗 -->
    <a-modal
      v-model:visible="addModalVisible"
      :title="isEdit ? '编辑合同' : '新增合同'"
      width="800px"
      :footer="null"
    >
      <a-form
        :model="formData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="协议名称" name="protocol">
          <a-input
            :value="formData.protocol"
            @input="formData.protocol = $event.target.value"
            placeholder="请输入协议名称"
          />
        </a-form-item>
        <a-form-item label="协议类型" name="protocolType">
          <a-radio-group
            v-model:value="formData.protocolType"
            :options="plainOptions"
          />
        </a-form-item>
        <a-form-item label="归属机构" name="comId">
          <a-tree-select
            v-model:value="formData.comId"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择归属机构"
          />
        </a-form-item>
        <a-form-item label="协议内容" name="agreementContent">
          <!-- <Editor
            :value="formData.contractContent"
            @input="formData.contractContent = $event"
          /> -->
          <UEditor
            v-model="formData.agreementContent"
            :height="300"
            width="100%"
            placeholder="请输入协议内容"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
          <a-space>
            <a-button type="primary" @click="handleSubmit">保存</a-button>
            <a-button @click="handleCancel">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import {
  SearchOutlined,
  PlusOutlined,
  UploadOutlined,
  LoadingOutlined,
} from '@ant-design/icons-vue';
import { getOperatorApi } from '#/api/core/statistical';
import * as netData from '#/api/core/setting';
import { message } from 'ant-design-vue';
import UEditor from '#/components/Editor/UEditor.vue';
import { getCompanyTree } from '#/api/core/develop';
// import Editor from '@tinymce/tinymce-vue';
import dayjs from 'dayjs';

onMounted(() => {
  getTableData();
});
type TreeNode = {
  key: string | number;
  label: string;
  value: string | number;
  isLeaf: boolean;
  children: TreeNode[];
};
const comanyList = ref<TreeNode[]>([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): TreeNode[] => {
      console.log(tree);
      return tree.map((item: any): TreeNode => {
        const processedItem: TreeNode = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    console.log(comanyList.value);
  });
};
const selectList = ref([]);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      // console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    // console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          // console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        // console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const searchForm = reactive<any>({
  comId: '',
  protocol: '',
  protocolType: '',
  agreementContent: '',
  agreementNumber: '',
  operatingTime: '',
});
const plainOptions = [
  {
    value: 0,
    label: '供热协议',
  },
  {
    value: 1,
    label: '停供协议',
  },
];
const columns = [
  {
    title: '归属机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '协议编号',
    dataIndex: 'agreementNumber',
    key: 'agreementNumber',
    align: 'center',
  },
  {
    title: '协议名称',
    dataIndex: 'protocol',
    key: 'protocol',
    align: 'center',
  },
  {
    title: '协议类型',
    dataIndex: 'protocolType',
    key: 'protocolType',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '操作时间',
    dataIndex: 'operatingTime',
    key: 'operatingTime',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
  },
];
const dataSource = ref([]);
const loading = ref<boolean>(false);
const imageUrl = ref<string>('');
const checked = ref<boolean>(false);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onSearch = () => {
  const query = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    operatingTime: searchForm.operatingTime
      ? `${dayjs(searchForm.operatingTime[0]).format('YYYY-MM-DD')},${dayjs(
          searchForm.operatingTime[1],
        ).format('YYYY-MM-DD')}`
      : '',
    comId: searchForm.comId ?? '',
    operator: searchForm.operator ?? '',
    protocol: searchForm.protocol ?? '',
    protocolType: searchForm.protocolType ?? '',
  };
  netData.getProtocolInfo(query).then((res: any) => {
    // console.log(res);
    dataSource.value = res.data;
    pagination.total = res.total;
  });
};
// 新增/编辑弹窗相关
const addModalVisible = ref(false);
const isEdit = ref(false);
const editId = ref('');
const formData = reactive({
  comId: '',
  protocol: '',
  protocolType: '',
  agreementContent: '',
});
const fileList = ref<any[]>([]);

// 显示新增弹窗
const showAddModal = () => {
  isEdit.value = false;
  editId.value = '';
  addModalVisible.value = true;
};

// 显示编辑弹窗
const showEditModal = (record: any) => {
  isEdit.value = true;
  editId.value = record.id;
  // 回填表单数据
  formData.comId = record.comId ?? '';
  formData.protocol = record.protocol ?? '';
  formData.protocolType = record.protocolType ?? '';
  formData.agreementContent = record.agreementContent ?? '';
  addModalVisible.value = true;
};

// 取消
const handleCancel = () => {
  addModalVisible.value = false;
  isEdit.value = false;
  editId.value = '';
  // 重置表单
  formData.comId = '';
  formData.protocol = '';
  formData.protocolType = '';
  formData.agreementContent = '';
  fileList.value = [];
  imageUrl.value = '';
  checked.value = false;
};

// 提交
const handleSubmit = () => {
  console.log(formData);
  if (!formData.protocol) {
    message.error('请输入协议名称');
    return;
  }
  if (!formData.agreementContent) {
    message.error('请输入协议内容');
    return;
  }

  const query = {
    comId: formData.comId,
    protocol: formData.protocol,
    protocolType: formData.protocolType,
    agreementContent: formData.agreementContent,
  };

  // 根据是否为编辑模式调用不同的接口
  const apiCall = isEdit.value
    ? netData.editProtocolInfo({ ...query, id: editId.value })
    : netData.addProtocolInfo(query);

  apiCall
    .then((res: any) => {
      console.log(res);
      if (res === 1) {
        console.log('提交数据:', formData, fileList.value);
        message.success(isEdit.value ? '编辑成功' : '保存成功');
        handleCancel();
        onSearch(); // 刷新列表
      }
    })
    .catch((error) => {
      console.error('操作失败:', error);
      message.error(isEdit.value ? '编辑失败' : '保存失败');
    });
};

// 删除
const confirmDelete = (id: any) => {
  // 这里可以添加删除确认弹窗
  // console.log('删除记录:', id);
  netData.delProtocolInfo(id).then((res: any) => {
    if (res === 1) {
      message.success('删除成功');
      onSearch(); // 刷新列表
    }else{
      message.error('删除失败');
    }
  });
  // 实现删除逻辑
};

// 文件上传前处理
const beforeUpload = (file: any) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小不能超过10MB!');
    return false;
  }
  fileList.value = [...fileList.value, file];
  return false; // 阻止自动上传
};

// 移除文件
const handleRemove = (file: any) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};

// 图片上传状态变化
const handleChange = (info: any) => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    loading.value = false;
    imageUrl.value = info.file.response.url || info.file.thumbUrl;
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('上传失败');
  }
};
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
